package com.example.his.api.mis.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.his.api.db.dao.OrderDao;
import com.example.his.api.db.pojo.OrderEntity;
import com.example.his.api.front.service.PaymentService;
import com.example.his.api.mis.controller.form.SearchOrderByPageForm;
import com.example.his.api.mis.service.OrderService;
import com.example.his.api.utils.PageUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;

@Service("MisOrderServiceImpl")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Resource
    private PaymentService paymentService;

    @Override
    public PageUtils searchByPage(SearchOrderByPageForm form) {
        Page<HashMap> page = PageHelper.startPage(form.getPage(), form.getLength())
                .doSelectPage(() -> baseMapper.searchByPage(form));
        return new PageUtils(page.getResult(), page.getTotal(), form.getPage(), form.getLength());
    }


    @Override
    @Transactional
    public int checkPaymentResult(String[] outTradeNoArray) {
        int i = 0;
        for (String outTradeNo : outTradeNoArray) {
            String transactionId = paymentService.searchPaymentResult(outTradeNo);
            if (transactionId != null) {
                int rows = baseMapper.updatePayment(new HashMap() {{
                    put("outTradeNo", outTradeNo);
                    put("transactionId", transactionId);
                }});
                i += rows;
            }
        }
        return i;
    }


    @Override
    @Transactional
    public int deleteById(int id) {
        int rows = baseMapper.deleteById(id);
        return rows;
    }


    @Override
    @Transactional
    public int updateRefundStatusById(int id) {
        int rows = baseMapper.updateRefundStatusById(id);
        return rows;
    }
}
